package article

import (
	"context"
	"forum/internal/common"
	"forum/internal/domain/event/article"
	"forum/intr/domain/repo"
	"forum/pkg/saramax"
	"github.com/IBM/sarama"
	"time"
)

type InteractiveReadEventConsumer struct {
	client    sarama.Client
	interRepo repo.InteractiveRepository
}

func NewInteractiveReadEventConsumer(client sarama.Client, interRepo repo.InteractiveRepository) *InteractiveReadEventConsumer {
	return &InteractiveReadEventConsumer{
		client:    client,
		interRepo: interRepo,
	}
}

func (i *InteractiveReadEventConsumer) Start() error {
	cg, err := sarama.NewConsumerGroupFromClient("intr", i.client)
	if err != nil {
		return err
	}
	go func() {
		er := cg.Consume(context.Background(),
			[]string{common.TopicReadEvent},
			saramax.NewReadHandler[article.ReadEvent](i.Consume))
		if er != nil {
			//TODO log
		}
	}()
	return err
}

func (i *InteractiveReadEventConsumer) Consume(msg *sarama.ConsumerMessage,
	event article.ReadEvent) error {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	return i.interRepo.IncrReadCnt(ctx, "article", event.Aid)
}
